"""
Adaptive Speech watermarking using the wavelet transform
"""
#
# wt_lsb.py
#
# Copyright (C) 2012 Robert Buj Gelonch
# Copyright (C) 2012 David Megias Jimenez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
__author__ = "Robert Buj Gelonch, and David Megias Jimenez"
__copyright__ = "Copyright 2012, Robert Buj Gelonch and David Megias Jimenez"
__credits__ = ["Robert Buj Gelonch", "David Megias Jimenez"]
__license__ = "GPL"
__version__ = "3"
__maintainer__ = "Robert Buj"
__email__ = "rbuj@uoc.edu"
__status__ = "Development"
__docformat__ = 'plaintext'

from numpy import abs
from numpy import array
from numpy import bitwise_and
from numpy import copysign
from numpy import int16
from numpy import log2
from numpy import ones
from numpy import sign
from pywt import dwt
from pywt import idwt
from uoc.wave.watermark.schemes.msb import detection_function as D_MSB
from uoc.wave.watermark.schemes.msb import embedding_function as E_MSB
from uoc.wave.watermark.schemes.msb import retrieval_function as R_MSB

def embedding_function(S, w, P_watermarking_sheme):
    """
    embedding_function
    """
    # Apply the wavelet transform in the original audio signal
    cA, cD = dwt(S, P_watermarking_sheme['numtaps'])
    # Add the watermark message in MSB of cD component
    cD_w = E_MSB(cD, w, P_watermarking_sheme)
    s = idwt(cA, cD_w, P_watermarking_sheme['numtaps'])
    return array(s)

def retrieval_function(s, P_watermarking_sheme):
    """
    Return the embedded watermark message within the watermarked
    audio signal
    """
    # Apply the wavelet transform in the original audio signal
    msb = log2(P_watermarking_sheme['max_value'] + 1) - 1
    cA, cD = dwt(s, P_watermarking_sheme['numtaps'])
    R = R_MSB(cD, P_watermarking_sheme)
#    print binary_repr((2 ** (msb))-1, width=16)
#    print binary_repr(2 ** msb, width=16)
    cD2 = copysign(bitwise_and(abs(cD).astype(int16), \
                   ones(len(cD), dtype=int) * ((2 ** msb)-1).astype(int)), \
                   sign(cD))
    return idwt(cA, cD2, P_watermarking_sheme['numtaps']), R

def detection_function(s, w, P_watermarking_sheme):
    """
    Evaluate whether the watermarked signal contains the water-
    marked message
    """
    return D_MSB(s, w, P_watermarking_sheme)

